<!--
 * @Author: your name
 * @Date: 2021-12-20 09:50:49
 * @LastEditTime: 2021-12-20 09:50:50
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \cscec-pms-admin\src\views\technical\ShiGroup\Approval\signAudit.vue
-->
<template>
  <base-breadcrumb>
    <a-form-model
      ref="form"
      :model="form"
      :rules="rules"
      hide-required-mark
      :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
      :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"
    >
      <a-card>
        <title-name title="审批"></title-name>
        <div style="margin-left:60px">
          <title-name style="font-size:14px" title="会签信息"></title-name>
        </div>

        <custom-form :form="form" :formList="auditFormList" :editModel="'0'">
          <template v-slot:table>
            <a-form-model-item class="mb20" label=" " :colon="false">
              <table class="customtable">
                <thead class="form-item">
                  <tr>
                    <th style="width:60px">序号</th>
                    <th style="min-width:300px ;text-align: center" colSpan="2">
                      指标
                    </th>
                    <th>修改意见</th>
                  </tr>
                </thead>
                <tbody>
                  <template v-for="(item, index) in form.basicInformationDTOS">
                    <tr :key="index">
                      <td>{{ item.basicIndexDTOS[0].idx }}</td>
                      <td :rowspan="item.basicIndexDTOS.length">{{ item.name }}</td>
                      <td>{{ item.basicIndexDTOS[0].indexName }}</td>
                      <td>
                        <BaseInput v-model="item.basicIndexDTOS[0].content" />
                      </td>
                    </tr>
                    <tr v-for="(ele, inx) in item.basicIndexDTOS.length - 1" :key="index + '-' + inx">
                      <td>{{ item.basicIndexDTOS[ele].idx }}</td>
                      <td>{{ item.basicIndexDTOS[ele].indexName }}</td>
                      <td>
                        <BaseInput v-model="item.basicIndexDTOS[ele].content" />
                      </td>
                    </tr>
                  </template>
                </tbody>
              </table>
            </a-form-model-item>
          </template>
        </custom-form>
        <div class="btn_box">
          <a-button :loading="loading.REJECT" @click="handleSave('REJECT')">拒绝上报</a-button>
          <a-button type="primary" :loading="loading.PASS" class="ml12" @click="handleSave('PASS')">同意上报</a-button>
        </div>
      </a-card>
      <a-card>
        <template>
          <title-name title="审批流程信息" />
          <div class="btns-wrapp mb20">
            <a-button type="primary" @click="visibleState.auditProcess = true"> 审批流程图 </a-button>
          </div>
          <a-spin tip="流程信息加载中..." :spinning="flowRequesting">
            <a-table :columns="columnApprove" :data-source="approveInfos" bordered>
              <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
              <template slot="opinions" slot-scope="text">
                <a-tooltip placement="topLeft">
                  <template slot="title">
                    <span> {{ text }}</span>
                  </template>
                  <span> {{ text }}</span>
                </a-tooltip>
              </template>
            </a-table>
          </a-spin>
        </template>
      </a-card>
      <a-card>
        <TitleName title="基本信息" />

        <a-row :gutter="24">
          <a-col :md="8" :sm="8">
            <a-form-model-item label="所属分公司" prop="branchComId">
              <SelectSubCompany v-model="form.branchComId" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="所属项目" prop="projectId">
              <SelectProject
                v-model="form.projectId"
                disabled
                key-value="branchComId"
                :form="form"
                :clear-list="true"
                @change="handleProjectChanged"
              />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="填报类型" prop="reportingType">
              <a-select v-model="form.reportingType" placeholder="请选择" disabled>
                <a-select-option value="0">
                  计划内填报
                </a-select-option>
                <a-select-option value="1">
                  计划外填报
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item prop="partIds" label="分部分项">
              <SelectTreeSubItem disabled :projectId="form.projectId" v-model="form.partIds" />
            </a-form-model-item>
          </a-col>
          <a-col v-if="form.reportingType == '0'" :md="8" :sm="8">
            <a-form-model-item label="方案名称" prop="planSelection" required>
              <a-select v-model="form.planSelection" placeholder="请选择" disabled>
                <a-select-option v-for="item in planItemList" :key="item.id" :value="item.id">
                  {{ item.constructionName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col v-else :md="8" :sm="8">
            <a-form-model-item label="方案名称">
              <BaseInput v-model="form.schemeName" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="方案类型" prop="programTypeId" required>
              <a-select v-model="form.programTypeId" placeholder="请选择" disabled>
                <a-select-option v-for="item in typeOption" :key="item.id" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="现行版本" prop="currentVersion">
              <BaseInput v-model="form.currentVersion" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="报审表编号" prop="reviewCode">
              <BaseInput v-model="form.reviewCode" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="文件编码" prop="fileCode">
              <BaseInput v-model="form.fileCode" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="编制人员" prop="compiler">
              <SelectPersonByProject v-model="form.compiler" :project-id="form.projectId" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :md="24" :sm="24">
            <a-form-model-item label="方案概况" prop="programOverview">
              <BaseInput v-model="form.programOverview" type="textarea" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="正文页数" prop="bodyPages">
              <BaseInput v-model="form.bodyPages" :max-length="9" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="附件页数" prop="attachmentPages">
              <BaseInput v-model="form.attachmentPages" :max-length="9" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="是否为专业分包方案">
              <a-switch v-model="form.whetherProfessionalSubcontracting" default-checked disabled />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8" v-if="form.whetherProfessionalSubcontracting">
            <a-form-model-item label="计划讲评时间">
              <BaseInput disabled v-model="form.evaluationDate" />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="是否涉及重大费用诉求">
              <a-switch v-model="form.whetherMajorExpense" default-checked disabled />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="附件">
              <upload-list
                disabled
                :business-code="'TM05'"
                :upload-arrys.sync="form.fileInfoVOList"
                :is-close="type !== 'view'"
                multiple
                @fileArrysData="handleFileUploaded"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-card>
      <!-- 页脚操作栏 -->
      <div class="btn_box page-btn-right-top">
        <a-button @click="handleActiveClose">关闭</a-button>
      </div>
      <ApprovalDetails
        :title="'审批流程信息'"
        :business-id="id"
        :visible="visibleState.auditProcess"
        @cancel="visibleState.auditProcess = false"
        @confirm="visibleState.auditProcess = false"
      />
    </a-form-model>
  </base-breadcrumb>
</template>

<script>
import SelectPersonByProject from '@/components/Select/SelectPersonByProject'
import UploadList from '@/components/UploadList'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目
import TitleName from '@/components/TitleName/index.vue'
import { getOption, addList, editList, deleteList, getSignDetails, putSign } from '@/api/technical/approval'
import { listOption } from '@/api/technical/approvalPlan'
import { getProcessNodeList, completeTask } from '@/api/process'
import { submitConstructionScoreForm } from '@/api/design/designManage'
import Vue from 'vue'
import moment from 'moment'
import { columnApprove } from './model.js'
import fileTable from './fileTable.vue'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import ApprovalDetails from '@/components/approvalDetails'
import { getOrgEmployeesListBy } from '@/api/commons'
import SelectTreeSubItem from '@/components/Select/SelectTreeSubItem'
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    TitleName,
    SelectSubCompany,
    SelectProject,
    UploadList,
    SelectPersonByProject,
    fileTable,
    ApprovalDetails,
    SelectTreeSubItem
  },
  data() {
    const validReportType = (rule, value, callback) => {
      const validKey = this.form.reportingType === '1' ? 'programTypeId' : 'planSelection'
      if (!this.form[validKey]) {
        callback(new Error('请选择'))
      } else {
        callback()
      }
    }
    return {
      visibleState: {
        auditProcess: false
      },
      flowRequesting: false,
      loading: {
        isDraft: false,
        isSubmit: false
      },
      loadingBtn: {
        PASS: false,
        REJECT: false
      },
      form: {
        reportingType: '0',
        compiler: '',
        branchComId: '',
        projectId: '',
        fileInfoVOList: [],
        programTypeId: ''
      },
      columnApprove,
      rules: {
        branchComId: [{ required: true, message: '请选择', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择', trigger: 'change' }],
        reportingType: [{ required: true, message: '请选择', trigger: 'change' }],
        planSelection: [{ validator: validReportType, trigger: 'change' }],
        programTypeId: [{ validator: validReportType, trigger: 'change' }],
        currentVersion: [{ required: true, message: '请输入', trigger: 'change' }],
        reviewCode: [{ required: true, message: '请输入', trigger: 'change' }],
        fileCode: [{ required: true, message: '请输入', trigger: 'change' }],
        compiler: [{ required: true, message: '请选择', trigger: 'change' }],
        programOverview: [{ required: true, message: '请输入', trigger: 'change' }],
        bodyPages: [{ required: true, message: '请输入', trigger: 'change' }],
        attachmentPages: [{ required: true, message: '请输入', trigger: 'change' }]
      },
      planItemList: [], // 计划项列表
      type: '',
      id: '',
      disabled: false,
      typeOption: [],
      tableData: [],
      ScoreTableData: [],
      selectedRowKeys: '',
      selectedRows: '',
      totalScore: 100,
      result: '优秀',
      vetoHeaderId: '',
      columnsScore: [],
      columns: [],
      scoreInformation: '',
      scorecount: '',
      vetoList: [],
      // formDatas: {},
      approveInfos: [], // 审批流程信息
      procInstId: '', //当前流程实例ID
      taskId: '', //当前流程节点ID
      processName: '', //流程名称
      taskName: '', //当前流程节点名称
      taskDefKey: '', //任务标识
      currentTime: '', //当前审批时间
      currentUser: '', //当前审批人
      flowRequesting: false,
      detailUrl: null, //详情地址

      assignType: '', //节点类型   0 变量获取 1 处理人 2 候选人 3 候选组 4 会签
      assignCode: '', //候选组编码 岗位编码
      assignLevel: '', //层级 项目部 PD 分公司 BC 公司 CO
      businessType: '', //业务类型 0 项目,

      conclusionData: []
    }
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        selectedRows: this.selectedRows, // 当前行所有数据
        onChange: this.onSelectChange
      }
    },
    auditFormList() {
      return [
        {
          keyName: 'projectName',
          type: 'BaseInput',
          label: '项目名称',
          disabled: true,
          span: 8
        },
        {
          keyName: 'currentUser',
          type: 'BaseInput',
          label: '责任人',
          disabled: true,
          span: 8
        },
        {
          keyName: 'currentTime',
          type: 'BaseInput',
          label: '会签时间',
          disabled: true,
          span: 8
        },
        {
          slot: true,
          customItemSlot: true,
          keyName: 'table',
          span: 24
        }
      ]
    }
  },

  created() {
    this.form.user = JSON.parse(sessionStorage.getItem('ycloud-user_info')).username
    this.id = this.$route.query.id
    this.getSignDetails()
    this.clickTypeOption()
    const {
      type,
      code,
      level,
      btype,
      businessId,
      procInstId,
      name,
      processName,
      detailUrl,
      taskId,
      taskDefKey
    } = this.$route.query
    if (type) {
      this.assignType = type
      this.assignCode = code
      this.assignLevel = level
      this.businessType = btype
    }
    this.id = businessId
    if (!this.id) {
      this.$error({ content: '无指定业务ID，将自动关闭' })
      setTimeout(() => {
        window.close()
      }, 1500)
      return
    }
    this.procInstId = procInstId
    this.form.currentUser = Vue.getAcloudProvider().getUserInfo().name
    this.taskName = decodeURIComponent(name)
    this.processName = decodeURIComponent(processName)
    document.title = this.processName + '-' + this.taskName
    if (detailUrl) {
      this.detailUrl = decodeURIComponent(detailUrl)
    }
    this.taskId = taskId
    this.taskDefKey = taskDefKey
    this.form.currentTime = moment().format('YYYY-MM-DD HH:mm')

    //获取流程节点执行情况
    this.getProcessNodes()
  },
  methods: {
    initStyle() {
      try {
        setTimeout(() => {
          const requireDom = document.querySelectorAll('.ant-input')
          console.log(requireDom)
          requireDom.forEach(item => {
            item.parentNode.classList.add('requiredFormItem') // 找到'.ant-form-item-children'元素添加样式
          })
        }, 0)
      } catch {}
    },
    //流程节点信息
    getProcessNodes() {
      this.flowRequesting = true
      getProcessNodeList({ procInstId: this.procInstId, pageNo: 1, pageSize: 100 })
        .then(res => {
          if (res.code === 200) {
            const data = res.data
            const userIds = data.map(d => {
              if (d.formData) {
                d.formData = JSON.parse(d.formData)
              }
              return d.assignee
            })
            getOrgEmployeesListBy({ userIds, delete: true }).then(employees => {
              this.flowRequesting = false
              res.data.forEach(r => {
                employees.data.some(e => {
                  if (e.userId === r.assignee) {
                    r.userName = e.name
                    return true
                  }
                })
              })
              this.approveInfos = res.data
            })
          }
        })
        .catch(() => {
          this.flowRequesting = false
        })
    },
    handleProjectChanged() {
      this.getOption()
    },
    handleFileUploaded(list) {
      this.form.fileInfoVOList = [...list]
    },

    listOption() {
      listOption({ type: '5' }).then(res => {
        this.typeOption = res.data
      })
      listOption({ type: '8' }).then(res => {
        this.conclusionData = res.data
      })
    },
    clickTypeOption() {
      this.listOption()
    },
    getOption() {
      const { projectId } = this.form
      if (!projectId) return
      const params = {
        projectId: projectId
      }
      getOption(params).then(res => {
        if (res.code === 200) {
          this.planItemList = res.data
        }
      })
    },

    getSignDetails() {
      if (this.id) {
        getSignDetails({ id: this.id, code: this.$userInfo().currentPost.postCode }).then(res => {
          this.form = {
            ...this.form,
            ...res.data
          }
          this.form.programTypeId = res.data.programTypeId
          this.form.planSelection = res.data.planSelectionId
          this.form.whetherMajorExpense = res.data.whetherMajorExpense === 'true' ? true : false
          this.form.whetherProfessionalSubcontracting =
            res.data.whetherProfessionalSubcontracting === 'true' ? true : false
          this.$nextTick(() => {
            this.form.projectId = res.data.projectId
            this.getOption()
            this.initStyle()
          })
          // this.initTable(res)
        })
      }
    },

    // 处理增、删、改操作
    handleSave(status) {
      if (this.loadingBtn[status]) return

      if (status == 'PASS') {
        let falg = false
        this.form.basicInformationDTOS?.forEach(i => {
          i.basicIndexDTOS?.forEach(e => {
            console.log(e)
            if (e.content == '' || e.content == null) {
              falg = true
            }
          })
        })

        if (falg) {
          this.$message.warning('请填写修改意见')
          return
        }

        this.handelApproval(status)
      } else {
        this.handelUnApproval(status)
      }
    },
    handelApproval(staus) {
      // 审批通过
      const _this = this
      const confirmWin = this.$confirm({
        title: '警告提醒！',
        content: '确定审批通过？',
        okType: 'danger',
        onOk() {
          return new Promise((resolve, reject) => {
            _this
              .submit(false, staus)
              .then(() => {
                resolve()
                confirmWin.destroy()
              })
              .catch(() => reject)
          }).catch(() => this.$error({ content: '审批提交失败，请稍后重试' }))
        },
        onCancel() {}
      })
    },
    notifyParent() {
      window.opener.postMessage('finish', window.location.origin)
    },
    handelUnApproval(staus) {
      // 审批不通过
      const _this = this
      const confirmWin = this.$confirm({
        title: '警告提醒！',
        content: '确定审批不通过？',
        okType: 'danger',
        onOk() {
          return new Promise((resolve, reject) => {
            _this
              .submit(true, staus)
              .then(() => {
                resolve()
                confirmWin.destroy()
              })
              .catch(() => reject)
          }).catch(() => this.$error({ content: '审批提交失败，请稍后重试' }))
        },
        onCancel() {}
      })
    },
    async submit(reject) {
      delete this.form.status
      const res = await putSign(this.form.basicInformationDTOS)

      if (res.data.code != 200) return

      if (!reject) {
        this.form.opinions = '同意上报'
      } else if (reject) {
        this.form.opinions = '拒绝上报'
      }

      const data = {
        formData: {
          opinions: this.form.opinions,
          reject
        },
        procInstId: this.procInstId, //当前流程实例ID
        taskId: this.taskId, //当前流程节点ID
        userId: Vue.getAcloudProvider().getUserInfo().id
      }
      if (reject) {
        data['variables'] = { reject: true }
      }
      return completeTask(data)
        .then(res => {
          if (res.status === 200) {
            this.notifyParent() // 通知父窗口
            // this.$success({
            //   content: '审批提交成功，即将自动关闭当前窗口',
            //   onOk() {
                window.close()
            //   }
            // })
            // setTimeout(() => {
            //   window.close()
            // }, 2000)
          } else {
            this.$error({ content: '审批提交失败，请稍后重试' })
          }
          return res
        })
        .catch(err => {
          return err
        })
    }
  }
}
</script>

<style lang="less">
.foot-btn {
  display: flex;
  justify-content: flex-end;
}
.radio-box {
  .ant-radio-wrapper {
    position: static !important;
  }
  .ant-radio-group {
    margin-top: 3% !important;
    display: flex;
  }
}
.input {
  width: 100%;
}
.footer {
  float: right;
  margin-right: 10px;
}
.footer button {
  margin-left: 10px;
}
.title {
  border-left: 4px solid #1890ff;
  font-weight: bold;
  font-size: 14px;
  margin-bottom: 20px;
  padding-left: 10px;
  height: 18px;
  line-height: 20px;
  margin-left: 20px;
  margin-top: 20px;
}
.customtable {
  width: 100%;
  border: 1px solid gainsboro;

  thead {
    background: rgb(244, 244, 244);

    th {
      padding: 10px;
      border: 1px solid gainsboro;
    }
  }

  tbody {
    td {
      padding: 10px;
      border: 1px solid gainsboro;
    }
  }
}
.requiredFormItem {
  .ant-input-search {
    input {
      cursor: default;
    }
  }
  .ant-input-number {
    border: none;
  }
  .ant-input-number-input {
    border: 1px solid #d9d9d9;
    border-radius: 4px;
  }
  .ant-input:not([disabled]),
  .ant-time-picker-input,
  .ant-select:not(.ant-select-disabled) .ant-select-selection,
  .ant-calendar-picker-input,
  .ant-input-number-input,
  .ant-cascader-picker {
    border-color: #e4ac0b;
    background-color: #fff9e8;
  }
  //输入框的禁用颜色，
  //2020//11/30备注：去掉了.ant-calendar-picker-input,这个
  .ant-input-disabled,
  .ant-input-number-disabled .ant-input-number-input,
  .ant-time-picker-input[disabled] {
    border-color: #d9d9d9 !important;
    background-color: #f5f5f5 !important;
  }
}
</style>
